package com.xoa.service.document;

import com.xoa.dao.document.DocumentMapper;
import com.xoa.dao.document.DocumentModelMapper;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.dao.workflow.FlowFormTypeMapper;
import com.xoa.model.document.Document;
import com.xoa.model.document.DocumentModel;
import com.xoa.model.document.DocumentModelWithBLOBs;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.outDocument.DocumentType;
import com.xoa.model.outDocument.OutDocument;
import com.xoa.model.outDocument.OutDocumentAtt;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowFast;
import com.xoa.model.workflow.FlowFormType;
import com.xoa.model.workflow.FlowRun;
import com.xoa.model.workflow.FlowRunPrcs;
import com.xoa.service.WFE.WFERunner.WFEFlowRunInfo;
import com.xoa.service.WFE.WFERunner.WFERunner;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.http.HttpClientUtil;
import com.xoa.util.page.PageParams;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.xpath.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/3/30.
 */
@Service
public class OutDocumentService {

    @Autowired
    private AttachmentMapper attachmentMapper;

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private WFEFlowRunInfo wfeFlowRunInfo;

    @Autowired
    protected WFERunner wfeRunner;

    @Autowired
    private FlowFormTypeMapper flowFormTypeMapper;

    @Autowired
    private DocumentModelMapper documentMapper;

    /**
     * 作者: 张航宁
     * 日期: 2018/3/30
     * 说明: 获取外网公文数据
     */
    public JSONObject getHttpDocuments(String userId, PageParams pageParams) {
        JSONObject json = new JSONObject();
        try {
            String appKey = "MyEyv5j1";
            String testUserId = "8ae882a25c7bfabc015c9bb664ac24e3";

            String page = "";
            String pageSize = "";
            if (pageParams != null) {
                if (pageParams.getPage() != null && !pageParams.getPage().equals(0)) {
                    page = String.valueOf(pageParams.getPage() - 1);
                }
                if (pageParams.getPageSize() != null && pageParams.getPageSize() != 0) {
                    pageSize = String.valueOf(pageParams.getPageSize());
                }
            }

            if (StringUtils.checkNull(userId)) {
                userId = testUserId;
            }

            String sign = DigestUtils.shaHex(userId + appKey);

            String url = "http://wxoa.xmhcedu.gov.cn/activiti/business/hcedu-document-flow-interface!personalTask.action?userId=" + userId + "&sign=" + sign + "&start=" + page + "&limit=" + pageSize;
            json = HttpClientUtil.httpGet(url);

            json.put("flag", json.get("success"));
            json.remove("success");


        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 作者: 张航宁
     * 日期: 2018/4/1
     * 说明: 根据id获取
     */
    public JSONObject getDocById(String userId, String id) {
        JSONObject json = new JSONObject();
        try {
            String appKey = "MyEyv5j1";
            String testUserId = "8ae882a25c7bfabc015c9bb664ac24e3";

            if (StringUtils.checkNull(userId)) {
                userId = testUserId;
            }

            String sign = DigestUtils.shaHex(id + appKey);

            String url = "http://wxoa.xmhcedu.gov.cn/activiti/business/hcedu-document-flow-interface!detail.action?userId=" + userId + "&sign=" + sign + "&id=" + id;

            json = HttpClientUtil.httpGet(url);
            json.put("flag", json.get("success"));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 作者: 张航宁
     * 日期: 2018/4/1
     * 说明: 接收公文
     * 参数说明：id 为待办中的businessKey   taskId为待办中的id
     */
    public ToJson<Object> receiveDoc(HttpServletRequest request, HttpServletResponse response, String userId, String id, String taskId, String flag, String beginUser, String jingbanUser) {
        ToJson json = new ToJson();
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            String sqlType = "xoa" + (String) request.getSession().getAttribute("loginDateSouse");

            String appKey = "MyEyv5j1";
            String testUserId = "8ae882a25c7bfabc015c9bb664ac24e3";

            if (StringUtils.checkNull(userId)) {
                userId = testUserId;
            }

            // 获取单条公文jsonObject
            JSONObject docById = getDocById(userId, id);
            // 获取单条公文详细数据 并造型
            Map<String, Object> outDocumentMap = (Map<String, Object>) docById.get("data");
            List<Map<String, Object>> attachmentLists = (List<Map<String, Object>>) outDocumentMap.get("attachmentList");

            OutDocumentAtt outDocumentAtt = new OutDocumentAtt();
            List<Attachment> attachments = new ArrayList<Attachment>();
            for (Map<String, Object> map1 : attachmentLists) {
                outDocumentAtt.setId(String.valueOf(map1.get("id")));
                outDocumentAtt.setName(String.valueOf(map1.get("name")));
                attachments.add(downloadAtt(outDocumentAtt, response, request));
            }

            // formId=152  flowId=252
            Map<String, Object> formMap = new HashMap<String, Object>();

            // 新建一条流程 并获取runId
            ToJson<FlowFast> flowFastToJson = wfeRunner.getWfeFlowRunInfo().workFastAdd(user, 252, 1, "1", "", request, sqlType, String.valueOf(outDocumentMap.get("documentTitle")), "0");

            FlowFast object = (FlowFast) flowFastToJson.getObject();
            Integer runId = object.getFlowRun().getRunId();
            FlowRun flowRun = wfeRunner.getWfeFlowRun().find(runId);

            // 插入公文
            DocumentModelWithBLOBs document = new DocumentModelWithBLOBs();
            document.setTitle(flowRun.getRunName());
            document.setCreater(user.getUserId());
            document.setCreateDept(String.valueOf(user.getDeptId()));
            String cureTime = DateFormat.getCurrentTime2();
            document.setPrintDate(cureTime);
            document.setDocumentType("1");
            document.setDispatchType("");
            document.setFlowId(flowRun.getFlowId());
            document.setRunId(runId);
            document.setCurUserId(user.getUserId());
            document.setFlowRunName(flowRun.getRunName());

            documentMapper.insertSelective(document);

            if ("1".equals(flag)) {
                newDocumentFlow(outDocumentMap, formMap, runId, flowRun);
            } else if ("2".equals(flag)) {
                newDocumentFlow(outDocumentMap, formMap, runId, flowRun);
                //wfeRunner.getWfeFlowRunInfo().savework(runId.toString(), flowRun.getRunName(), "252", "1", "1", "2", flowRun.getBeginTime(), beginUser, jingbanUser, "", user, "1", "0");

            }

            // 添加附件到流程上
            if(attachments!=null&&attachments.size()>0){
                Object[] objects = FileUploadUtil.reAttachmentAll(attachments);
                Map<String,Object> updateAttMap = new HashMap<String,Object>();
                updateAttMap.put("attachmentId",  objects[0].toString());
                updateAttMap.put("attachmentName",  objects[1].toString());
                updateAttMap.put("runId", runId);
                wfeRunner.getWfeFlowRun().updateAttachment(updateAttMap);
            }

            // 生成sign
            String sign = DigestUtils.shaHex(id + taskId + userId + appKey);
            // 更新接收公文信息
            String updateUrl = "http://wxoa.xmhcedu.gov.cn/activiti/business/hcedu-document-flow-interface!perusalComplete.action?userId=" + userId + "&sign=" + sign + "&id=" + id + "&taskId=" + taskId;
            // 发送请求
            JSONObject jsonObject = HttpClientUtil.httpGet(updateUrl);


            json.setObject(flowFastToJson.getObject());
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("err");
        }
        return json;
    }

    /**
     * 作者: 张航宁
     * 日期: 2018/4/9
     * 说明: 新建一条公文流程
     */
    private void newDocumentFlow(Map<String, Object> outDocumentMap, Map<String, Object> formMap, Integer runId, FlowRun flowRun) {
        formMap.put("runId", runId);
        formMap.put("tableName", "flow_data_252");
        // 查询表单数据
        Map<String, Object> select = workMapper.select(formMap);

        Boolean updateFlag = true;
        if (select == null) {
            select = new HashMap<String, Object>();
            updateFlag = false;
            formMap.put("tableSchema","xoa1001");
            List<String> strings = workMapper.showColumns(formMap);
            if(strings!=null&&strings.size()>0){
                for (String column:strings) {
                    select.put(column,"");
                }
                select.remove("ID");
                select.remove("FLOW_AUTO_NUM");
                select.remove("FLOW_AUTO_NUM_MONTH");
                select.remove("FLOW_AUTO_NUM_YEAR");
            }
        }

        // 文件类型
        Map<String, Object> documentType = (Map<String, Object>) outDocumentMap.get("documentType");
        select.put("DATA_5", documentType.get("name"));
        // 登记时间
        String registrationTime = "";
        if(outDocumentMap.get("registrationTime")!=null){
            registrationTime = DateFormat.getStrTime((int) ((Long) outDocumentMap.get("registrationTime") / 1000));
        }
        select.put("DATA_32", registrationTime);

        // 缓急程度
        Map<String, Object> urgentLevel = (Map<String, Object>) outDocumentMap.get("urgentLevel");
        select.put("DATA_6", urgentLevel.get("name"));
        // 文号
        select.put("DATA_33", outDocumentMap.get("receiptNumber"));

        // 是否公开
        select.put("DATA_34", (Boolean)outDocumentMap.get("open") ? "是" : "否");

        // 标题
        select.put("DATA_12", outDocumentMap.get("documentTitle"));
        // 内容
        select.put("DATA_13", outDocumentMap.get("contentText"));

        // 截至日期
        select.put("DATA_35","");
        // 上级部门
        select.put("DATA_2","");


        select.put("RUN_ID",runId);
        select.put("BEGIN_USER",flowRun.getBeginUser());
        select.put("BEGIN_TIME",flowRun.getBeginTime());
        select.put("RUN_NAME",flowRun.getRunName());

        List<String> keys = new ArrayList<String>();
        List<Object> values = new ArrayList<Object>();

        Set<String> strings = select.keySet();

        for (String key:strings) {
            keys.add(key);
            values.add(select.get(key));
        }

        select.put("keys",keys);
        select.put("values",values);
        select.put("tableName","flow_data_252");

        if(updateFlag){
            workMapper.update(select);
        }else{
            workMapper.insert(select);
        }
    }

    /**
     * 作者: 张航宁
     * 日期: 2018/4/9
     * 说明: 下载附件
     */
    public Attachment downloadAtt(OutDocumentAtt outDocumentAtt, HttpServletResponse response, HttpServletRequest request) {

        Attachment attachment = new Attachment();
        String downloadUrl = "http://wxoa.xmhcedu.gov.cn/system/attachment!download.action?id=" + outDocumentAtt.getId();

        // 获取库
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        String company = "xoa" + SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class,redisSessionId);
        // 获取上传路径
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String os = System.getProperty("os.name");
        StringBuilder sb = new StringBuilder();
        StringBuffer buffer=new StringBuffer();
      /*  if (os.toLowerCase().startsWith("win")) {
            sb = sb.append(rb.getString("upload.win"));
        } else {
            sb = sb.append(rb.getString("upload.linux"));
        }*/
        if(os.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            sb=sb.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }
        //当前年月
        String ym = new SimpleDateFormat("yyMM").format(new Date());


        //存储路径
        if (StringUtils.checkNull(sb.toString())) {
            String a = request.getRealPath("");
            sb.append(a);
            sb.append(System.getProperty("file.separator")).
//                    append("attach").
//                    append(System.getProperty("file.separator")).
                    append(company).append(System.getProperty("file.separator")).
                    append("workflow").append(System.getProperty("file.separator")).append(ym);
        } else {
            sb.append(System.getProperty("file.separator")).
//                    append("attach").
//                    append(System.getProperty("file.separator")).
                    append(company).append(System.getProperty("file.separator")).
                    append("workflow").append(System.getProperty("file.separator")).append(ym);
        }
        // 路径地址
        String path = sb.toString();

        String attachID =String.valueOf( Math.abs((int) System.currentTimeMillis()));
        String newFileName = attachID + "." + outDocumentAtt.getName();
        //获得模块名
        int moduleID = 0;
        for (ModuleEnum em : ModuleEnum.values()) {
            if (em.getName().equals("workflow")) {
                moduleID = em.getIndex();
            }
        }

        byte mid = (byte) moduleID;

        try {
            // 下载文件
            File file = HttpClientUtil.downLoadFromUrl(downloadUrl, newFileName, path);

            if (file != null) {
                // 保存进数据库
                attachment = new Attachment();
                attachment.setAttachId(attachID);
                attachment.setModule(mid);
                attachment.setAttachFile(outDocumentAtt.getName());
                attachment.setAttachName(outDocumentAtt.getName());
                attachment.setYm(ym);
                attachment.setAttachSign(new Long(0));
                attachment.setDelFlag((byte) 0);
                attachment.setPosition((byte) 2);
                attachment.setIsImage((byte) 0);
                attachment.setFileSize(String.valueOf(file.length()));
                attachment.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

                attachmentMapper.insertSelective(attachment);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return attachment;
    }
}
